#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>
#include <vector>
#include <cstdio>
#include <ctime>
using namespace std;
int ticket = 1000;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *BuyTicket(void *args)
{
    std::string name = static_cast<char *>(args);
    while (true)
    {

        pthread_mutex_lock(&lock);

        pthread_cond_wait(&cond, &lock);

        std::cout << name << "->ticket: " << ticket << std::endl;
        ticket--;
        pthread_mutex_unlock(&lock);
    }
}


int main()
{

#define NUM 4
    vector<pthread_t> tids(NUM);

    for (size_t i  = 0; i < NUM; ++i)
    {
        char name[64];
        snprintf(name, sizeof name, "thread %d", i + 1);
        pthread_create(&tids[i], nullptr, BuyTicket, (void *)name);
    }

    while (true)
    {
        sleep(1);
        cout << "main thread is wakeuping a thread" << endl;
        pthread_cond_broadcast(&cond);
    }

    for (const auto &tid : tids)
    {
        pthread_join(tid, nullptr);
    }

    return 0;
}
